#include "../include/DirScanner.hpp"

DirScanner::DirScanner()
{
}

DirScanner::~DirScanner()
{
}

vector<string> &DirScanner::getFiles()
{
    return _files;
}

void DirScanner::traverse(const string &dirName)
{
    DIR *pDir = opendir(dirName.c_str()); // c_str()：返回指向存储了字符串的空终止字符数组的指针
    if (!pDir)
    {
        cout << "opendir failed" << endl;
#ifdef DEBUG
        perror("DirScanner::traverse()_opendir() failed");
        cout << "dirName: " << dirName << endl;
#endif
        return;
    }

    struct dirent *pdirent;
    char buf[1024];
    // 实现 深度优先遍历 访问目录项
    while ((pdirent = readdir(pDir)))
    {
        // 排除.和..文件
        if (strcmp(pdirent->d_name, ".") == 0 || strcmp(pdirent->d_name, "..") == 0)
        {
            continue;
        }
        sprintf(buf, "%s%s%s", dirName.c_str(), "/", pdirent->d_name);
        if (pdirent->d_type == 4)
        {
            traverse(string(buf));
        }
        else
        {
            _files.push_back(string(buf));
        }
    }

    closedir(pDir);

    return;
}
